Variables declared with var
are function-scoped, meaning they are accessible within the entire function in which they are defined. If
a variable is declared using var
outside of any function, it becomes a global variable and is accessible throughout the entire JavaScript
program.
let
and const
were introduced in ECMAScript 6 (ES6) as a block-scoped alternative to var
. Variables declared
with let
have block scope, meaning they are limited to the block of code in which they are defined. A block is typically delimited by
curly braces {}
.
Variables declared with const
are also block-scoped, similar to let
. However, const
variables are immutable,
meaning their value cannot be changed after assignment. This applies to the binding between the variable name and its value, but it does not mean the
value itself is immutable if it is an object or an array.
A variable declared with let
or const
is said to be in a "temporal dead zone", meaning the period between entering a
scope and declaring a let
or const
variable. During this phase, accessing the variable results in a
ReferenceError
. This helps catch potential errors and encourages proper variable declaration.
Unlike let
and const
, variables declared with var
are subject to "hoisting", which means that they are moved
to the top of their scope during the compilation phase, even if the actual declaration is placed lower in the code.
Hoisting can sometimes lead to unexpected behavior. For example, variables declared with var
are accessible before they are declared,
although they will have the value undefined
until the declaration is reached.
The distinction between the variable types created by var
and by let
is significant, and a switch to let
will help alleviate many of the variable scope issues which have caused confusion in the past.
Because these new keywords create more precise variable types, they are preferred in environments that support ECMAScript 2015. However, some
refactoring may be required by the switch from var
to let
, and you should be aware that they raise SyntaxError
s
in pre-ECMAScript 2015 environments.
This rule raises an issue when var
is used instead of const
or let
.
var color = "blue"; // Noncompliant
var size = 4; // Noncompliant
You should declare your variables with either const
or let
depending on whether you are going to modify them
afterwards.
const color = "blue";
let size = 4;